package com.wing.product.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductPack;
import com.wing.product.model.request.ProductPackForm;
import com.wing.product.model.response.ProductPackVO;
import com.wing.product.service.ProductPackService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@Api(value = "app-产品包装管理", tags = "app-产品包装管理")
@RestController("appProductPackController")
@RequestMapping("product/app/productPack")
@RequiredArgsConstructor
@Slf4j
public class ProductPackController {

    @Autowired
    private ProductPackService productPackService;

    @ApiOperation(value = "查询所有产品包装规格", notes = "搜索")
    @GetMapping("/list")
    public JsonResult<List<ProductPackVO>> list(String skuCode){
        Map params=new HashMap();
        params.put("skuCode",skuCode);
        List<ProductPackVO> list=productPackService.list4app(params);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询所有产品包装", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value = "计量编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPacklist")
    public PageResult<ProductPackVO> getPacklist(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String code
            ,String name
            ,Long productType
    ){

        Page<ProductPack> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        paramMap.put("code",code);
        paramMap.put("name",name);
        paramMap.put("productType",productType);

        IPage<ProductPackVO> list = productPackService.pageList4app(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加产品包装", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductPackForm.Add.class) ProductPackForm productPackForm) {

        if (productPackService.add(productPackForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改产品包装", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductPackForm.Update.class) ProductPackForm productPackForm) {

        ProductPack productPack = productPackService.getById(productPackForm.getId());
        if(productPack == null){
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductPack.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productPackForm, productPack, copyOptions);
        if (productPackService.updateById(productPack)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除产品包装", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productPackId", value = "产品包装id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long productPackId) {

        if (productPackService.removeById(productPackId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "启用产品包装计量方案", notes = "启用")
    @com.wing.common.annotation.RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/enable")
    public JsonResult enable(@Validated(ProductPackForm.Add.class) ProductPackForm productPackForm) {

        ProductPack productPack=new ProductPack();
        productPack.setId(productPackForm.getId());
        productPack.setIsDeleted(true);
        if (productPackService.updateById(productPack)) {
            return JsonResult.success("启用成功");
        }
        return JsonResult.fail("启用失败");
    }

    @ApiOperation(value = "停用产品包装计量方案", notes = "停用")
    @com.wing.common.annotation.RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/disable")
    public JsonResult disable(@Validated(ProductPackForm.Add.class) ProductPackForm productPackForm) {

        ProductPack productPack=new ProductPack();
        productPack.setId(productPackForm.getId());
        productPack.setIsDeleted(false);
        if (productPackService.updateById(productPack)) {
            return JsonResult.success("停用成功");
        }
        return JsonResult.fail("停用失败");
    }

    @ApiOperation(value = "删除产品包装计量方案", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "产品包装计量方案id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/delBatch" )
    public JsonResult delete(String ids) {

        if (StringUtils.isNotBlank(ids)){
            List<Long> idList=new ArrayList<>();
            String[] idArray=ids.split(",");
            for (int i=0;i<idArray.length;i++){
                idList.add(Long.valueOf(idArray[i]));
            }
            if (productPackService.remove(new QueryWrapper<ProductPack>().in("id",idList))) {
                return JsonResult.success("删除成功");
            }
        }else{
            return JsonResult.fail("请选择数据");
        }

        return JsonResult.fail("删除失败");
    }
    @GetMapping("/getProductPackById")
    public JsonResult<ProductPackVO> getProductPackById(Long packId){

        ProductPackVO info = productPackService.get4appById(packId);
        return JsonResult.success(info);
    }

    @ApiOperation(value = "查询所有包装方案", notes = "查询")
    @GetMapping("/getAll")
    public JsonResult<ProductPack> getAll(){

        QueryWrapper<ProductPack> wrapper = new QueryWrapper<>();
        wrapper.select("id","name","base_rate");
        List<ProductPack> pack = productPackService.list(wrapper);
        return JsonResult.success(pack);
    }

    @ApiOperation(value = "通过单位id查询包装", notes = "查询")
    @GetMapping("/getByUnitId")
    public JsonResult<ProductPack> getByUnitId(Long productUnitId){

        QueryWrapper<ProductPack> wrapper = new QueryWrapper<>();
        wrapper.eq("product_unit_id",productUnitId);
        List<ProductPack> list = productPackService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "通过类型id查询包装", notes = "查询")
    @GetMapping("/getByProductTypeId")
    public JsonResult<ProductPack> getByProductTypeId(Long productTypeId){

        QueryWrapper<ProductPack> wrapper = new QueryWrapper<>();
        wrapper.eq("product_type",productTypeId);
        wrapper.select("id","name");
        List<ProductPack> list = productPackService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询包装单位", notes = "查询")
    @GetMapping("/getPackUnit")
    public JsonResult<ProductPackVO> getPackUnit(Long id){

        ProductPackVO productPackVO = null;
        try {
            productPackVO = productPackService.getPackUnitById(id);
        } catch (Exception e) {
            log.error("查询包装单位失败！",e.getMessage());
            return JsonResult.fail("包装单位获取失败");
        }

        return JsonResult.success(productPackVO);
    }
}
